import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart' hide Form;
import 'package:get/get.dart';
import 'package:orginone/dart/extension/index.dart';
import 'package:orginone/components/XImage/components/icon.dart';
import 'package:orginone/components/EmptyWidget/EmptyWidget.dart';
import 'package:orginone/components/form/form_widget/form_tool.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/thing/standard/form.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/routers/router_const.dart';
import 'package:orginone/utils/log/log_util.dart';

import '../../XButton/XButton.dart';
import '../../XText/XText.dart';

//表单数据列表界面
class FormDataView extends StatefulWidget {
  const FormDataView({
    super.key,
    required this.xForm,
    this.form,
    this.showType,
    required this.type
  });
  final XForm xForm;
  final Form? form;
  final String? showType;
  final int? type;

  @override
  State<FormDataView> createState() => _FormDataViewState();
}

class _FormDataViewState extends State<FormDataView> {
  final List _listDatas = [];
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    loadData(refresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return _buildFormDataView(widget.xForm);
  }

  Widget _buildFormDataView(XForm xform) {
    if (widget.form == null) {
      return Container();
    }
    return _formDataView(xform);
  }

  loadData({bool refresh = false}) async {
    XLogUtil.d('loadData');
    if (refresh) {
      _listDatas.clear();
    }
    List newData = await FormTool.loadFormDatas(widget.form, _listDatas.length, widget.type!);
    _listDatas.addAll(newData);
    setState(() {});
  }

  _formDataView(XForm xform) {
    return "three" == widget.showType ? (
        /*? EmptyWidget(heightva: 260,)
        : */(_listDatas.isNotEmpty && 1 == _listDatas.length) ? Column(
          children: [
                FormDataItem(
                  datas: _listDatas[0],
                  form: widget.form,
                ),
          ],
        ) : (_listDatas.isNotEmpty && 2 == _listDatas.length) ? Column(
          children: [
            FormDataItem(
              datas: _listDatas[0],
              form: widget.form,
            ),
            FormDataItem(
              datas: _listDatas[1],
              form: widget.form,
            ),
          ],
        ) : Column(
          children: [
            FormDataItem(
              datas: _listDatas[0],
              form: widget.form,
            ),
            FormDataItem(
              datas: _listDatas[1],
              form: widget.form,
            ),
            FormDataItem(
              datas: _listDatas[2],
              form: widget.form,
            ),
          ],
        )
    ) : EasyRefresh(
        header: const MaterialHeader(),
        footer: const MaterialFooter(),
        onRefresh: () async {
          loadData(refresh: true);
        },
        onLoad: loadData,
        scrollController: _scrollController,
        child: _listDatas.isEmpty
            ? EmptyWidget()
            : ListView.builder(
          scrollDirection: Axis.vertical,
          itemBuilder: (context, index) {
            List<FieldModel> models =  _listDatas[index];
            return FormDataItem(
              datas: models,
              form: widget.form,
            );
          },
          itemCount: _listDatas.length,
        ));
  }
}

class FormDataItem extends StatelessWidget {
  const FormDataItem({super.key, required this.datas, required this.form});

  final List<FieldModel> datas;
  final Form? form;

  @override
  Widget build(BuildContext context) {
    return _buildSubFormItem();
  }

  _buildSubFormItem() {
    return <Widget>[
      ..._buildField(),
      XButton.iconCustomText(
        icon: IconWidget.icon(
          Icons.call_made,
          color: XColors.primary,
          size: 16,
        ),
        text: '  查看详情',
        iconLeft: true,
        textColor: Colors.black,
        bgcolor: Colors.transparent,
        // textSize: 14,
        // textWeight: FontWeight.w400,
        // textColor: XColors.primary,
        onPressed: () => toDetail(datas, form),
      )
    ]
        .toColumn(crossAxisAlignment: CrossAxisAlignment.start)
        .paddingOnly(left: 10, right: 10, top: 10)
        .backgroundColor(XColors.lightPrimary) //
        .marginSymmetric(horizontal: 10, vertical: 5)
        .borderRadius(all: 10)
        .clipRRect(all: 10, topLeft: 10);
  }

  List<Widget> _buildField() {
    if (datas.isEmpty) {
      return [Container()];
    }
    List<FieldModel> fileds = datas;
    // LogUtil.e(fileds
    //     .map((e) => {"name": e.name, "value": e.value, "type": e.valueType})
    //     .toList());
    fileds = (fileds.isNotEmpty && fileds.length > 5)
        ? fileds.sublist(0, 5)
        : fileds;
    List<Widget> ws = [];

    for (var i = 0; i < fileds.length; i++) {
      FieldModel fieldModel = fileds[i];
      var w = FutureBuilder<String>(
        builder: (context, snapshot) {
          if (snapshot.connectionState != ConnectionState.done &&
              !snapshot.hasData) {
            return Container();
          }
          var content = snapshot.data ?? "";

          FieldModel fieldModel = fileds[i];

          Widget row = <Widget>[
            Text(
              '${fieldModel.name}:  ',
              style: const TextStyle(color: XColors.gray_99),
            ),
            Expanded(
              child: Wrap(
                alignment: WrapAlignment.start,
                children: [
                  XText.fieldValue(
                    "null" == content ? "" : content,
                  ),
                ],
              ),
            ),
          ]
              .toRow(crossAxisAlignment: CrossAxisAlignment.start)
              .paddingBottom(i == fileds.length - 1 ? 0 : 5);

          return row;
        },
        future: FormTool.buildFieldValue(fieldModel),
      );
      ws.add(w);
    }
    return ws;
  }

  //跳转到详情
  toDetail(List<FieldModel> fileModels, Form? form) {
    form?.fields = fileModels;
    // form?.metadata.name = '详情';
    RoutePages.to(path: Routers.formDetailPreview, data: form);
  }
}
